<template>
	<form-container title="绑定邮箱号" :width="700" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formState" :rules="formRules" layout="vertical">
			<a-form-item label="产线编码：" name="code">
				<a-input v-model:value="formState.code" placeholder="请输入产线编码" allow-clear />
			</a-form-item>
			<a-form-item label="产线名称：" name="name">
				<a-input v-model:value="formState.name" placeholder="请输入产线名称" allow-clear />
			</a-form-item>
			<a-form-item label="所属车间：" name="workshopId">
				<a-select v-model:value="formState.workshopId" placeholder="请选择所属车间" :options="workshopOptions"
					:loading="workshopLoading" allow-clear />
			</a-form-item>
			<a-form-item label="描述：" name="description">
				<a-textarea v-model:value="formState.description" placeholder="请输入描述" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmitline">保存</a-button>
		</template>
	</form-container>
</template>

<script setup name="updatePassword">
import { required } from '@/utils/formRules'
import lineApi from '@/api/workshop/lineApi.js'
import workshopApi from '@/api/workshop/workshopApi.js' // 假设有车间API
import { onMounted, ref } from 'vue'

// 定义emit事件
const emit = defineEmits({ successful: null })
// 默认是关闭状态
const visible = ref(false)
const formRef = ref()
// 表单数据
const formState = ref({})
const submitLoading = ref(false)

// 车间下拉选项
const workshopOptions = ref([])
const workshopLoading = ref(false)

// 获取车间列表
const getWorkshopList = async () => {
	try {
		workshopLoading.value = true
		const res = await workshopApi.worklist() // 假设API有list方法获取车间列表
		workshopOptions.value = res.records.map(item => ({
			label: item.name,
			value: item.id
		}))
	} catch (error) {
		console.error('获取车间列表失败', error)
	} finally {
		workshopLoading.value = false
	}
}

// 在组件挂载时获取车间列表
onMounted(() => {
	getWorkshopList()
})

// 打开抽屉
const onOpen = (email) => {
	visible.value = true
	formState.value = email
}
// 关闭抽屉
const onClose = () => {
	visible.value = false
}
// 表单校验规则
const formRules = {
	code: [required('请输入产线编码')],
	name: [required('请输入产线名称')],
	workshopId: [required('请选择所属车间')]
}

// 提交数据
const onSubmitline = async () => {
	try {
		await formRef.value.validateFields()
		submitLoading.value = true
		const formData = {
			id: formState.value.id,
			code: formState.value.code,
			name: formState.value.name,
			workshopId: formState.value.workshopId,
			description: formState.value.description,
		}
		// 提交数据
		await lineApi.lineedit(formData)
		formRef.value.resetFields()
		visible.value = false
		emit('successful', formData)
	} catch (error) {
		console.error('提交失败', error)
	} finally {
		submitLoading.value = false
	}
}

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
	onOpen
})
</script>

<style scoped></style>